{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "pqMl9Ouxf6yn"
   },
   "source": [
    "# Data drift dashboard in jupyter notebook"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "8FP6JHGUf6ys"
   },
   "outputs": [],
   "source": [
    "import io\n",
    "import numpy as np\n",
    "import os\n",
    "import pandas as pd\n",
    "from pathlib import Path\n",
    "import requests\n",
    "import zipfile\n",
    "\n",
    "from datetime import datetime\n",
    "from sklearn import datasets, ensemble\n",
    "\n",
    "from evidently.pipeline.column_mapping import ColumnMapping\n",
    "from evidently.report import Report\n",
    "from evidently.metric_preset import DataDriftPreset\n",
    "from evidently.metric_preset import TargetDriftPreset\n",
    "from evidently.metric_preset import DataQualityPreset\n",
    "from evidently.metric_preset.regression_performance import RegressionPreset \n",
    "\n",
    "from evidently.metrics import (\n",
    "    RegressionQualityMetric,\n",
    "    RegressionPredictedVsActualScatter,\n",
    "    RegressionPredictedVsActualPlot,\n",
    "    RegressionErrorPlot,\n",
    "    RegressionAbsPercentageErrorPlot,\n",
    "    RegressionErrorDistribution,\n",
    "    RegressionErrorNormality,\n",
    "    RegressionTopErrorMetric,\n",
    "    RegressionErrorBiasTable,\n",
    "    \n",
    "    DatasetSummaryMetric,\n",
    "    ColumnSummaryMetric,\n",
    "    DatasetMissingValuesMetric,\n",
    "    DatasetCorrelationsMetric\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "x3OWHRQ0f6yv"
   },
   "source": [
    "## Bicycle Demand Data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Download and extract (unzip) data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Yx-GhFajUgNA"
   },
   "source": [
    "This step automatically downloads the bike dataset from UCI. This version is slightly different from the dataset used in Kaggle competition. If you want the example to be identical to the one in the Evidently blog \"How to break a model in 20 days\", you can manually download the dataset from Kaggle: https://www.kaggle.com/c/bike-sharing-demand/data \n",
    "\n",
    "And add this code:\n",
    "\n",
    "raw_data['mnth'] = raw_data.index.map(lambda x : x.month)\n",
    "\n",
    "raw_data['hr'] = raw_data.index.map(lambda x : x.hour)\n",
    "\n",
    "raw_data['weekday'] = raw_data.index.map(lambda x : x.weekday() + 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !wget https://archive.ics.uci.edu/static/public/275/bike+sharing+dataset.zip -P data/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !unzip data/bike+sharing+dataset.zip -d data/"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "uMLMel0Cf6yw"
   },
   "outputs": [],
   "source": [
    "raw_data = pd.read_csv(\"data/hour.csv\", header=0, sep=',', parse_dates=['dteday'], index_col='dteday')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "pNwLFltuf6yx",
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "raw_data.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get weeks number\n",
    "days = len(raw_data.index.unique())\n",
    "weeks = days / 7\n",
    "\n",
    "print(f'days = {days}; weeks = {weeks}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4VypH7uAf6yz"
   },
   "source": [
    "## Regression Model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Config"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "REF_MONTH_START = '2011-01-01'\n",
    "REF_MONTH_END = '2011-01-28'\n",
    "\n",
    "CUR_MONTH_START = '2011-01-29'\n",
    "CUR_MONTH_END = '2011-02-28'\n",
    "\n",
    "# CUR_WEEK_START = '2011-01-29'\n",
    "# CUR_WEEK_END = '2011-02-04'\n",
    "# CUR_WEEK_START = '2011-02-05'\n",
    "# CUR_WEEK_END = '2011-02-11'\n",
    "CUR_WEEK_START = '2011-02-12'\n",
    "CUR_WEEK_END = '2011-02-18'\n",
    "\n",
    "target = 'cnt'\n",
    "prediction = 'prediction'\n",
    "numerical_features = ['temp', 'atemp', 'hum', 'windspeed', 'hr', 'weekday']\n",
    "categorical_features = ['season', 'holiday', 'workingday']\n",
    "\n",
    "reports_dir = Path('reports') / f'{CUR_WEEK_START}_{CUR_WEEK_END}'\n",
    "reports_dir.mkdir(exist_ok=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9YMdccRpf6y3"
   },
   "source": [
    "### Model training"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "T8jbMDVwf6y4"
   },
   "outputs": [],
   "source": [
    "reference = raw_data.loc[REF_MONTH_START:REF_MONTH_END]\n",
    "current = raw_data.loc[CUR_MONTH_START:CUR_MONTH_END]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "SQLQTJy7f6y4",
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "reference.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "im2Bqd3zf6y5"
   },
   "outputs": [],
   "source": [
    "regressor = ensemble.RandomForestRegressor(random_state = 0, n_estimators = 50)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "bt_5Kfu-f6y5"
   },
   "outputs": [],
   "source": [
    "regressor.fit(reference[numerical_features + categorical_features], reference[target])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "-7b4UNq2f6y6"
   },
   "outputs": [],
   "source": [
    "ref_prediction = regressor.predict(reference[numerical_features + categorical_features])\n",
    "current_prediction = regressor.predict(current[numerical_features + categorical_features])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "tt79FK5Mf6y6"
   },
   "outputs": [],
   "source": [
    "reference['prediction'] = ref_prediction\n",
    "current['prediction'] = current_prediction"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4i2oy0k1f6y7"
   },
   "source": [
    "# Model Monitoring"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Rg0JipUif6y7"
   },
   "outputs": [],
   "source": [
    "column_mapping = ColumnMapping()\n",
    "\n",
    "column_mapping.target = target\n",
    "column_mapping.prediction = prediction\n",
    "column_mapping.numerical_features = numerical_features\n",
    "column_mapping.categorical_features = categorical_features"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model performance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "6G7KzxSxf6y9"
   },
   "outputs": [],
   "source": [
    "regression_performance_report = Report(metrics=[RegressionPreset()])\n",
    "\n",
    "regression_performance_report.run(\n",
    "    reference_data=reference,\n",
    "    current_data=current.loc[CUR_WEEK_START:CUR_WEEK_END],\n",
    "    column_mapping=column_mapping\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "2kN2qqaLf6y-"
   },
   "outputs": [],
   "source": [
    "model_performance_report_path = reports_dir / 'model_performance.html'\n",
    "regression_performance_report.save_html(model_performance_report_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "62qRRKmhf6y9"
   },
   "source": [
    "##  Target drift"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "afFgUlwvf6y-"
   },
   "outputs": [],
   "source": [
    "target_drift_report = Report(metrics=[TargetDriftPreset()])\n",
    "target_drift_report.run(\n",
    "    reference_data=reference,\n",
    "    current_data=current.loc[CUR_WEEK_START:CUR_WEEK_END],\n",
    "    column_mapping=column_mapping\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "5AyuTggif6y_"
   },
   "outputs": [],
   "source": [
    "target_drift_report_path = reports_dir / 'target_drift.html'\n",
    "target_drift_report.save_html(target_drift_report_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "imlXej4of6zE"
   },
   "source": [
    "## Data drift"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "x-CrzsxSf6zE"
   },
   "outputs": [],
   "source": [
    "column_mapping = ColumnMapping()\n",
    "column_mapping.numerical_features = numerical_features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "cKdcopYPf6zE"
   },
   "outputs": [],
   "source": [
    "data_drift_report = Report(metrics=[DataDriftPreset()])\n",
    "data_drift_report.run(\n",
    "    reference_data=reference,\n",
    "    current_data=current.loc[CUR_WEEK_START:CUR_WEEK_END],\n",
    "    column_mapping=column_mapping\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Xy7Y6S8Af6zF"
   },
   "outputs": [],
   "source": [
    "data_drift_report_path = reports_dir / 'data_drift.html'\n",
    "data_drift_report.save_html(data_drift_report_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data quality"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "column_mapping = ColumnMapping()\n",
    "column_mapping.numerical_features = numerical_features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_quality_report = Report(metrics=[DataQualityPreset()])\n",
    "data_quality_report.run(\n",
    "    reference_data=reference,\n",
    "    current_data=current.loc[CUR_WEEK_START:CUR_WEEK_END],\n",
    "    column_mapping=column_mapping\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_quality_report_path = reports_dir / 'data_quality.html'\n",
    "data_quality_report.save_html(data_quality_report_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [
    "xnrzxRRnf6y_",
    "BAXuFSrTf6zC"
   ],
   "name": "bicycle_demand_monitoring.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "305.994px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
